<?php

namespace App\Http\Controllers\Basic;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;

class UploadController extends Controller
{
    //
    public function ueditor(Request $request)
    {

        switch($request->input('action'))
        {
            case 'config':
                return $this->_config();

            /* 上传图片 */
            case 'uploadimage':
                /* 上传涂鸦 */
            case 'uploadscrawl':
                /* 上传视频 */
            case 'uploadvideo':
                /* 上传文件 */
            case 'uploadfile':
                return $this->_upload($request);
                break;
        }

        echo $request->input('action');
    }

    private function _config()
    {

        $config = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents(public_path('packages/ue/php/config.json'))), true);

        return response()->json($config);
    }

    private function _upload($request)
    {
        $file = $request->file('upfile');

        if(empty($file))
        {
            $this->setStatus(30001);
            $this->setMsg('请选择上传的文件');
            return $this->response();
        }

        $storage = Storage::disk('admin');
        $path = config('admin.upload.directory.image').'/'.date('Y-m-d').'/'.uniqid().'.'.$file->clientExtension();
        $storage->put($path, file_get_contents($file->path()));
        $url = config('admin.upload.host').$path;

        $data['url'] = $url;
        $data['state'] = 'SUCCESS';
        return response()->json($data);
    }

    public function put(Request $request)
    {

        $file = $request->file('wangEditorH5File');
        $storage = Storage::disk('admin');

        $path = config('admin.upload.directory.image').'/'.date('Y-m-d').'/'.uniqid().'.'.$file->clientExtension();
        $storage->put($path, file_get_contents($file->path()));


        $url = config('admin.upload.host').$path;
        echo $url;
    }


    public function putImg(Request $request)
    {
        $file = $request->file('file');

        if(empty($file))
        {
            $this->setStatus(30001);
            $this->setMsg('请选择上传的文件');
            return $this->response();
        }

        $storage = Storage::disk(config('filesystems.default'));
        $path = '/'.date('Y-m-d').'/'.uniqid().'.'.$file->clientExtension();

        $im = Image::make($file->path());
        $im->save($file->path(), 70);
        $storage->put($path, file_get_contents($file->path()));
        $url = config('filesystems.base_url').$path;

        $this->setData(['url'=>$url]);
        return $this->response();
    }
}
